package com.zhh.srforum.interceptor;

import com.zhh.srforum.mapper.UserMapper;
import com.zhh.srforum.model.User;
import com.zhh.srforum.model.UserExample;
import com.zhh.srforum.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Zhao Haihang
 * @Date: 2020/11/20/20:35
 * @Description:
 */
@Component
public class SessionInterceptor  implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NotificationService notificationService;

    @Value("${gitee.redirect_uri}")
    private String redirect_uri;

    @Value("${gitee.client.id}")
    private String client_id;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object handler) throws Exception {
        //设置 context 级别的属性
        httpServletRequest.getServletContext().setAttribute("redirect_uri", redirect_uri);
        httpServletRequest.getServletContext().setAttribute("client_id", client_id);

        Cookie[] cookies = httpServletRequest.getCookies();
        if(cookies!=null && cookies.length!=0){
            for(Cookie cookie : cookies){
                if("token".equals(cookie.getName())){
                    String token = cookie.getValue();
                    UserExample userExample = new UserExample();
                    userExample.createCriteria()
                            .andTokenEqualTo(token);
                    List<User> users = userMapper.selectByExample(userExample);
                    if (users.size() != 0) {
                        HttpSession session = httpServletRequest.getSession();
                        session.setAttribute("user", users.get(0));
                        Long unreadCount = notificationService.unreadCount(users.get(0).getId());
                        session.setAttribute("unreadCount", unreadCount);
                    }
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
